Ext.define('truckplanner.controller.Yard', {
    
	extend: 'Ext.app.Controller',   
    	
    stores : ['Yards'],
    
    models : ['Yard'],
    
    views: ['yard.List','yard.Edit'],

	requires: ['truckplanner.view.yard.Edit', 'Ext.MessageBox'],
	
	refs: [
	       {ref: 'yardList', selector: 'yardlist'},
	       {ref: 'yardData', selector: 'yardlist dataview'},
	       {
	           ref: 'yardEditor', 
	           selector: 'yardeditor', 
	           autoCreate: true,
	           xtype: 'yardeditor'
	       },
	       {ref: 'yardForm', selector: 'yardeditor form'}
	],
	
	init: function() {
		this.control({
	        'yardlist button[action=remove]': {
	            click: this.removeYard
	        },
	        'yardlist button[action=edit]': {
	            click: this.editYard
	        },
	        'yardlist button[action=add]': {
	            click: this.addYard
	        },
	        'yardeditor button[action=cancel]': {
	            click: this.cancelEditor
	        },
	        'yardeditor button[action=ok]': {
	            click: this.saveYard
	        }
	    });
	}, 
	
	cancelEditor: function() {
		var editor = this.getYardEditor(),
    	form = this.getYardForm();
		form.form.reset();
		editor.hide();
		this.editedYard = null;
	},
	
	editYard: function() {
    	var list = this.getYardList(),
    	editor = this.getYardEditor(),
    	form = this.getYardForm(),
    	yard = list.getSelectionModel().getSelection()[0];
    	this.editedYard = yard;
    	fields = form.getForm().getFields();
        fields.each(function(field){
        	if(field.xtype != 'container' && field.xtype != 'button')
        		field.setValue(yard.get(field.getName()));
        });
    	editor.show();
    },
    
    addYard: function() {
    	this.editedYard = this.getYardModel().create({});
    	this.getYardEditor().show();    	
    },
    
	saveYard: function() {
    	var win = this.getYardEditor(),
		form = this.getYardForm(),
		yard = this.editedYard,
		store = this.getYardsStore();
    	fields = form.getForm().getFields();
        fields.each(function(field){
        	if(field.xtype != 'container' && field.xtype != 'button')
        		yard.set(field.getName(), field.getValue());
        });
        if(!yard.store){
    		store.add(yard);
    	}
        store.save();
        form.getForm().reset();
		win.hide();
    },
	
	removeYard: function() {
    	var list = this.getYardList();
    	yard = list.getSelectionModel().getSelection();
        if(yard.length > 0)
        {
        	Ext.MessageBox.confirm('Message', 'Etes-vous sure de vouloir le supprimer?' , this.removeYard2, this);	
        }
	},
	
	removeYard2 : function () {
		var store = this.getYardsStore();
     	store.remove(this.getYardList().getSelectionModel().getSelection()[0]);
     	store.save();
	}

});